package com.example.musicmodule.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.musicmodule.Callback.Callback;
import com.example.musicmodule.PlayApplication;
import com.example.musicmodule.entity.Music;
import com.example.musicmodule.ible.IMusic;
import com.example.musicmodule.util.MusicUrlUtil;
import com.example.musicmodule.util.RequestUtil;

import java.io.IOException;
import java.util.List;


/**
 * 播放音乐的服务
 */
public class PlayService extends Service {

    private MediaPlayer mp;
    private PlayApplication app;

    @Override
    public void onCreate() {
        super.onCreate();
        app=(PlayApplication)getApplication();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        PlayBinder playBinder=new PlayBinder();
//        app.music=playBinder;
        return playBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
//        if(mp!=null) {
//            mp.stop();
//            mp.reset();
//            mp.release();
//            mp=null;
//        }
        return super.onUnbind(intent);
    }

    public class PlayBinder extends Binder implements IMusic {

        @Override
        public void initMusic(List<Music> list) {
            app.songList.clear();
            //添加所有的音乐
            app.songList.addAll(list);
        }

        @Override
        public void pause() {
            if(mp!=null&&mp.isPlaying()) {
                mp.pause();
            }else {
                mp.start();
            }
            if (app.mm!=null){
                app.mm.notificationPlayStop();
                app.mm.updatePlayBar();
            }
        }

        @Override
        public void next() {
            //数据源
            int position=app.songPosition;
            if(position==(app.songList.size()-1)) {
                app.songPosition=0;
            } else {
                app.songPosition++;
            }
            stopPlay();
            play(app.songPosition);

        }

        @Override
        public void prev() {
            //数据源
            int position=app.songPosition;
            if(position==0) {
                app.songPosition=app.songList.size()-1;
            } else {
                app.songPosition--;
            }
            stopPlay();
            play(app.songPosition);
        }

        @Override
        public void seek(int i) {
           mp.seekTo(i);
        }

        @Override
        public boolean isPlay() {
            if (mp==null)return false;
            return mp.isPlaying();
        }

        @Override
        public int getduration() {
            return app.songList.get(app.songPosition).getFile_duration()*1000;
        }

        @Override
        public int getcurrenttime() {
            if (mp==null)return 0;
            return mp.getCurrentPosition();
        }

        private void stopPlay() {
            if(mp!=null) {
                mp.stop();
                mp.release();
                mp=null;
            }
        }
        /**
         * 播放
         */
        public void play(final int position) {
            stopPlay();
            if(app.songList.isEmpty()){
                return;
            }
            //获取数据之后进行播放
            mp=new MediaPlayer();
            //当前要播放的歌曲
            final Music currentSong=app.songList.get(position);
            app.songPosition=position;


            if (currentSong.getSong_id()!=0){
                RequestUtil r=new RequestUtil(PlayService.this, new Callback() {
                    @Override
                    public void callback(String s) {

                        JSONObject object= JSON.parseObject(s);
                        JSONObject bitrate = (JSONObject) object.get("bitrate");

                        currentSong.setUrl(bitrate.getString("file_link"));
                        app.songList.set(position,currentSong);
                        //解析出播放音乐的路径

                        Uri uri=Uri.parse(currentSong.getUrl());
                        try {
                            //设置数据源
                            mp.setDataSource(PlayService.this,uri);
                            //准备
                            mp.prepareAsync();
                            //播放
                            mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                                @Override
                                public void onPrepared(MediaPlayer mp) {
                                    mp.start();
                                    if(app.mm!=null){

                                        app.mm.updatePlayBar();
                                        app.mm.initNotification(currentSong);
                                    }
                                    if (app.iPlayer!=null){

                                        app.iPlayer.update();
                                    }
                                }
                            });
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
                r.getData( MusicUrlUtil.getMusicUrl(currentSong.getSong_id()));
                RequestUtil lrc=new RequestUtil(PlayService.this, new Callback() {
                    @Override
                    public void callback(String s) {
                        JSONObject object=JSONObject.parseObject(s);
                        String lrc=object.getString("lrcContent");
                        if (app.iPlayer!=null){
                            app.iPlayer.setLrc(lrc);
                            app.iPlayer.lrcShow();
                        }
                    }
                });
                lrc.getData(MusicUrlUtil.getLrcBySongId(currentSong.getSong_id()));

            }else {
                //解析出播放音乐的路径
                Uri uri = Uri.parse(currentSong.getUrl());
                try {
                    //设置数据源
                    mp.setDataSource(PlayService.this, uri);
                    //准备
                    mp.prepareAsync();
                    //播放
                    mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            mp.start();
                            if(app.mm!=null){

                                app.mm.updatePlayBar();
                                app.mm.initNotification(currentSong);
                            }
                            if (app.iPlayer!=null){

                                app.iPlayer.update();
                            }
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
